/*
 * @Author: wangtianyu wangtianyu@lierda.com
 * @Date: 2023-12-08 15:41:01
 * @LastEditors: wangtianyu wangtianyu@lierda.com
 * @LastEditTime: 2023-12-08 16:25:17
 * @FilePath: \kcm_c3_v1_0\lib\Application\Wireless\UdpTest.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "UdpTest.h"

#include "kkgui_base.h"
#include "kkgui_app.h"
#include "kkgui_virt_keyboard.h"

#include "WiFi.h"

char udp_serverIP[16] = "120.27.247.0"; //欲访问的服务端IP地址
uint16_t udp_serverPort = 2235;         //服务端口号

WiFiUDP udp_client; // 

uint8_t udp_read_buf[500];


void udp_client_ip_set(kkui_menu_event_e event, char* tab_name, void* param)
{
    if(event == ENTER_TAG)
    {
        uiVirtKeyboard(udp_serverIP, "IP Address", 15);
        uiBackAppLoop();
    }
    if(event == LOOP_RUN)
    {
        uiBackAppLoop();
    }
}


void udp_client_port_set(kkui_menu_event_e event, char* tab_name, void* param)
{
    if(event == ENTER_TAG)
    {
        char port_buf[6] = {0};
        sprintf(port_buf, "%d", udp_serverPort);
        uiVirtKeyboard(port_buf, "IP port", 5);
        sscanf(port_buf, "%d", &udp_serverPort);
        uiBackAppLoop();
    }
    if(event == LOOP_RUN)
    {
        uiBackAppLoop();
    }
}

void udp_client_loop(kkui_menu_event_e event, char* tab_name, void* param)
{
    if(event == ENTER_TAG)
    {
        memset(udp_read_buf, 0, 500);
    }
    if(event == LOOP_RUN)
    {
        int read_len = udp_client.parsePacket();
        if(read_len) //如果有数据可读取
        {
            memset(udp_read_buf, 0, 500);
            udp_client.read(udp_read_buf, read_len); //读取数据到换行符
        }

        uiDisClear(0);
        for(int ret = 0; ret < strlen((char *)udp_read_buf);)
        {
            uiShowString(1, 10 + 9 * (ret / 21), (char *)udp_read_buf + ret, 8, 1);
            ret += (strlen((char *)udp_read_buf + ret) > 21?21:strlen((char *)udp_read_buf + ret));
        }

        if(uiKeyGetValue(UI_KEY_ENTER_ID) == DOWN)
        {
            udp_client.beginPacket(udp_serverIP, udp_serverPort);
            udp_client.write((const uint8_t *)"kake control mini UDP TEST", strlen("kake control mini UDP TEST"));//把数据写入发送缓冲区
            udp_client.endPacket();//发送数据
        }
        
        if(uiKeyGetValue(UI_KEY_BACK_ID) == DOWN)
        {
            uiBackAppLoop();
        }
    }
    if(event == BACK_LIST)
    {
        udp_client.stop(); //关闭客户端
    }
}